package com.shiwei.is.manager;

import android.app.Application;
import android.content.Intent;
import android.util.Log;

import com.shiwei.is.ISApplication;
import com.shiwei.is.MainActivity;
import com.shiwei.is.R;
import com.shiwei.is.tools.Helper;

import java.util.concurrent.atomic.AtomicBoolean;

import dji.common.airlink.PhysicalSource;
import dji.common.error.DJIError;
import dji.common.error.DJISDKError;
import dji.sdk.airlink.AirLink;
import dji.sdk.airlink.OcuSyncLink;
import dji.sdk.base.BaseComponent;
import dji.sdk.base.BaseProduct;
import dji.sdk.sdkmanager.DJISDKInitEvent;
import dji.sdk.sdkmanager.DJISDKManager;

/**
 * File: null.java
 * Creator: dingpwen
 * Company: shiwei
 * Created on: 2021/3/24 15:48
 * Email: dingpwen@gmail.com
 * Details: TODO
 */
public class DJIDroneConnectManager {
    private static final String TAG = "ISApp-ConnectManager";
    //public static final String FLAG_CONNECTION_CHANGE = "dji_sdk_connection_change";
    public static final String FLAG_SOURCE_CHANGE = "dji_sdk_source_change";
    private final AtomicBoolean isRegistrationInProgress = new AtomicBoolean(false);
    private Application application = null;

    private DJIDroneConnectManager() {}
    private static class Holder{
        public static DJIDroneConnectManager instance = new DJIDroneConnectManager();
    }

    public static DJIDroneConnectManager getInstance() {
        return Holder.instance;
    }

    private final BaseComponent.ComponentListener mDJIComponentListener = isConnected -> notifyStatusChange();

    public void startSDKRegistration(Application application, RegCallback regCallback) {
        this.application = application;
        if (isRegistrationInProgress.compareAndSet(false, true)) {
            new Thread() {
                public void run() {
                    doRegistration(application, regCallback);
                }
            }.start();
        }
    }

    private void doRegistration(Application application, RegCallback regCallback) {
        DJISDKManager.getInstance().registerApp(application, new DJISDKManager.SDKManagerCallback(){
            @Override
            public void onRegister(DJIError error) {
                if(DJISDKError.REGISTRATION_SUCCESS == error) {
                    DJISDKManager.getInstance().startConnectionToProduct();
                    if(regCallback != null) {
                        regCallback.showMessage(R.string.boot_register_success);
                        regCallback.onRegSuccess();
                    }
                } else {
                    if(regCallback != null) {
                        regCallback.showMessage(R.string.boot_register_fail);
                    }
                }
                Log.v(TAG, error.getDescription());
                isRegistrationInProgress.set(false);
            }

            @Override
            public void onProductDisconnect() {
                if(regCallback != null) {
                    regCallback.showMessage("Product Disconnect");
                }
                notifyStatusChange();
            }

            @Override
            public void onProductConnect(BaseProduct baseProduct) {
                if(regCallback != null) {
                    regCallback.showMessage("Product Connect");
                }
                notifyStatusChange();
                setSourceForM300RTK();
            }

            @Override
            public void onProductChanged(BaseProduct baseProduct) {
                notifyStatusChange();
            }

            @Override
            public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent, BaseComponent newComponent) {
                if (newComponent != null) {
                    newComponent.setComponentListener(mDJIComponentListener);
                }
                Log.d(TAG,
                        String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
                                componentKey,
                                oldComponent,
                                newComponent));

                notifyStatusChange();
            }

            @Override
            public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {

            }

            @Override
            public void onDatabaseDownloadProgress(long current, long total) {

            }
        });
    }

    private void notifyStatusChange() {
        //Log.d("ISApp-connect", "do post");
        ISApplication.getEventBus().post(new MainActivity.ConnectivityChangeEvent());
    }

    private void setSourceForM300RTK(){
        if(Helper.isM300Product()) {
            AirLink airLink = DJISDKManager.getInstance().getProduct().getAirLink();
            if (airLink != null) {
                OcuSyncLink ocuSyncLink = airLink.getOcuSyncLink();
                if (ocuSyncLink != null) {
                    ocuSyncLink.assignSourceToPrimaryChannel(PhysicalSource.LEFT_CAM, PhysicalSource.FPV_CAM, djiError -> {
                        if (djiError != null) {
                            Log.e(TAG, "assignSource error:" + djiError.getDescription());
                        } else {
                            Log.d(TAG, "assignSource success");
                            application.sendBroadcast(new Intent(FLAG_SOURCE_CHANGE));
                        }
                    });
                }
            }
        }
    }

}
